from __future__ import annotations

import itertools
import json
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

from werkzeug.security import generate_password_hash

BASE_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = BASE_DIR / "data"
USERS_FILE = DATA_DIR / "users.json"
COMMENTS_FILE = DATA_DIR / "comments.json"

_post_id_counter = itertools.count(start=1)

SECTIONS: List[Dict[str, str]] = [
    {
        "id": "home",
        "title": "首页",
        "description": "展示平台核心价值、模块入口与最新动态。",
    },
    {
        "id": "introduction",
        "title": "学科简介",
        "description": "呈现信息工程学的概念、历史与基础知识框架。",
    },
    {
        "id": "shannon",
        "title": "奠基人",
        "description": "介绍 Claude Shannon 的生平、主要贡献与经典著作。",
    },
    {
        "id": "elements",
        "title": "五大要素",
        "description": "分解生成、传递、收集、存储、处理等要素及其案例。",
    },
    {
        "id": "applications",
        "title": "应用领域",
        "description": "包含机器人、自动驾驶等行业案例的可视化展示。",
    },
    {
        "id": "future",
        "title": "未来展望",
        "description": "探索未来趋势、技术路线与开放问题。",
    },
    {
        "id": "forum",
        "title": "讨论区",
        "description": "用于学术讨论、问题求助与社区互动的核心模块。",
    },
    {
        "id": "about",
        "title": "关于",
        "description": "提供项目背景、团队信息与版本更新内容。",
    },
]

INTRODUCTION: Dict[str, Any] = {
    "overview": "信息工程学关注信息的生成、传递、存储与应用，是现代社会数字化的基础学科。",
    "milestones": [
        {"year": 1948, "event": "Claude Shannon 提出信息论，为信息工程奠定理论基础"},
        {"year": 1960, "event": "通信技术快速发展，推动信息传输与编码应用"},
        {"year": 2000, "event": "互联网普及，信息工程应用走向大众生活"},
        {"year": 2020, "event": "人工智能与大数据驱动信息工程进入智能时代"},
    ],
    "statistics": [
        {"label": "高校相关专业", "value": "150+"},
        {"label": "行业覆盖", "value": "30+"},
        {"label": "核心技术方向", "value": "通信、计算、控制、智能"},
    ],
    "recommended": [
        {"title": "信息论基础", "link": "https://example.com/info-theory"},
        {"title": "现代通信原理", "link": "https://example.com/modern-communication"},
        {"title": "数据与智能", "link": "https://example.com/data-intelligence"},
    ],
}

FOUNDER_PROFILE: Dict[str, Any] = {
    "name": "Claude Shannon",
    "bio": "美国数学家、电气工程师，被誉为信息论之父，他在信息的数学定义、编码与传输方面做出革命性贡献。",
    "quotes": [
        "Information is the resolution of uncertainty.",
        "I visualize a time when we will be to robots what dogs are to humans.",
    ],
    "timeline": [
        {"year": 1916, "event": "出生于美国密歇根州盖洛德"},
        {"year": 1940, "event": "发表《通信系统的数学理论》奠定信息论基础"},
        {"year": 1950, "event": "发表《编程一台计算机下棋》引领人工智能探索"},
        {"year": 1978, "event": "获得国家科学奖章"},
    ],
    "contributions": {
        "information_theory": 95,
        "cryptography": 80,
        "communication": 90,
        "computing": 75,
        "mathematics": 70,
    },
    "papers": [
        {"title": "A Mathematical Theory of Communication", "year": 1948},
        {"title": "Communication Theory of Secrecy Systems", "year": 1949},
        {"title": "Programming a Computer for Playing Chess", "year": 1950},
    ],
}

ELEMENTS: List[Dict[str, Any]] = [
    {
        "id": "generation",
        "name": "信息生成",
        "summary": "从现实世界中采集或创造信息，强调数据源的准确与丰富。",
        "steps": ["采集需求分析", "选择传感设备", "数据采样与编码"],
        "cases": [
            {"title": "智慧城市传感网", "highlight": "部署环境监测传感器收集实时数据"},
            {"title": "舆情分析平台", "highlight": "通过爬虫采集社交媒体文本"},
        ],
    },
    {
        "id": "transmission",
        "name": "信息传递",
        "summary": "通过通信网络与协议完成信息的高效、安全传输。",
        "steps": ["信道选择", "调制编码", "纠错与加密"],
        "cases": [
            {"title": "5G 通信网络", "highlight": "低时延与高带宽保障车联网通信"},
            {"title": "深海光缆通信", "highlight": "跨洋信息传输的核心基础设施"},
        ],
    },
    {
        "id": "collection",
        "name": "信息收集",
        "summary": "对分散信息进行聚合与去噪，构建结构化数据资产。",
        "steps": ["数据清洗", "特征抽取", "多源融合"],
        "cases": [
            {"title": "物流供应链平台", "highlight": "整合仓储、运输与销售数据"},
            {"title": "医疗健康档案", "highlight": "跨医院共享诊疗数据"},
        ],
    },
    {
        "id": "storage",
        "name": "信息存储",
        "summary": "采用云存储或分布式数据库确保信息的可靠保留与快速访问。",
        "steps": ["存储模型设计", "冗余与备份", "安全访问控制"],
        "cases": [
            {"title": "对象存储系统", "highlight": "支持非结构化数据的弹性扩展"},
            {"title": "区块链账本", "highlight": "不可篡改记录确保数据可信"},
        ],
    },
    {
        "id": "processing",
        "name": "信息处理",
        "summary": "运用算法与计算平台对信息进行解析、挖掘与决策支持。",
        "steps": ["模型训练", "实时计算", "可视化呈现"],
        "cases": [
            {"title": "智能推荐引擎", "highlight": "基于深度学习的用户行为分析"},
            {"title": "工业故障预测", "highlight": "利用机器学习监测设备状态"},
        ],
    },
]

APPLICATIONS: List[Dict[str, Any]] = [
    {
        "id": 1,
        "title": "自动驾驶感知系统",
        "industry": "智能交通",
        "summary": "融合视觉、雷达与高精地图实现环境感知与决策。",
        "technologies": ["传感融合", "深度学习", "V2X"],
        "tags": ["自动驾驶", "信息融合"],
        "metrics": {"coverage": "200+ 城市测试", "latency": "20ms"},
        "detail": "系统集成多源传感设备并利用云端训练模型，实现 L3-L4 级自动驾驶。",
        "image": "https://images.unsplash.com/photo-1518770660439-4636190af475?w=800&q=80",
    },
    {
        "id": 2,
        "title": "智能医疗影像诊断",
        "industry": "智慧医疗",
        "summary": "基于深度神经网络实现 CT、MRI 的辅助诊断。",
        "technologies": ["医学影像", "AI 诊断", "云计算"],
        "tags": ["医疗", "智能诊断"],
        "metrics": {"accuracy": "95%", "hospitals": "80+"},
        "detail": "通过云端模型统一推理，辅助医生完成病灶识别与报告生成。",
        "image": "https://images.unsplash.com/photo-1485827404703-89b55fcc595e?w=800&q=80",
    },
    {
        "id": 3,
        "title": "工业互联网平台",
        "industry": "智能制造",
        "summary": "连接生产设备、业务系统与人员，实现数据驱动的协同制造。",
        "technologies": ["IoT", "边缘计算", "大数据分析"],
        "tags": ["制造业", "数字化转型"],
        "metrics": {"devices": "1.2万", "downtime": "-30%"},
        "detail": "平台支持实时监控、预测性维护与供应链可视化，提升产线效率。",
        "image": "https://images.unsplash.com/photo-1518770660439-4636190af475?w=800&q=80",
    },
    {
        "id": 4,
        "title": "多机器人协作与群控平台",
        "industry": "智能制造",
        "summary": "实现多台移动机器人在仓储/制造场景下的任务协同与路径规划。",
        "technologies": ["多机器人系统", "实时调度", "数字孪生"],
        "tags": ["机器人", "群控"],
        "metrics": {"robots": "300+", "效率提升": "35%"},
        "detail": "基于云边协同的调度引擎，可对仓储搬运机器人进行动态编队、障碍规避与任务分配，结合数字孪生实现实时监控与仿真。",
        "image": "https://images.unsplash.com/photo-1518770660439-4636190af475?w=800&q=80",
    },
    {
        "id": 5,
        "title": "低空经济综合运营平台",
        "industry": "低空经济",
        "summary": "打通空域管理、飞行计划与应急调度，实现低空运行安全高效。",
        "technologies": ["低空空管", "北斗定位", "遥感监测"],
        "tags": ["低空经济", "空域管理"],
        "metrics": {"飞行架次": "日均 120+", "响应时间": "-40%"},
        "detail": "平台集成北斗/GPS 定位、空域审批、气象数据与应急响应，实现无人机、eVTOL 运营的全流程数字化管理。",
        "image": "https://images.unsplash.com/photo-1473968512647-3e447244af8f?w=800&q=80",
    },
    {
        "id": 6,
        "title": "群控无人机巡检系统",
        "industry": "智慧能源",
        "summary": "利用多架无人机协同执行电力巡检与应急响应任务。",
        "technologies": ["群体智能", "计算机视觉", "5G 专网"],
        "tags": ["无人机", "巡检"],
        "metrics": {"覆盖线路": "500km+", "隐患识别率": "92%"},
        "detail": "通过 5G 专网与边缘计算节点，实现无人机编队巡检、异常自动识别与缺陷定位，广泛用于电网、油气管道等场景。",
        "image": "https://images.unsplash.com/photo-1473341304170-971dccb5ac1e?w=800&q=80",
    },
]

FUTURE_INSIGHTS: Dict[str, Any] = {
    "trends": [
        {"name": "泛在信息网络", "description": "6G 与卫星互联网构建全球无缝连接。"},
        {"name": "可信智能体", "description": "结合隐私计算与可信执行环境，保障数据安全。"},
        {"name": "人机协同", "description": "增强现实与数字孪生实现沉浸式协作体验。"},
    ],
    "kpis": [
        {"label": "全球数据量", "unit": "ZB", "values": {"2024": 175, "2030": 500}},
        {"label": "智能终端普及率", "unit": "%", "values": {"2024": 45, "2030": 80}},
    ],
    "roadmap": [
        {"year": 2025, "milestone": "构建跨行业数据互联标准"},
        {"year": 2027, "milestone": "实现信息基础设施智能自治"},
        {"year": 2030, "milestone": "形成可信普惠的信息社会体系"},
    ],
    "qa": [
        {
            "question": "信息工程未来最大的挑战是什么？",
            "answer": "在确保数据安全与隐私的前提下，实现跨域数据流通与协同创新。",
        },
        {
            "question": "如何参与行业生态？",
            "answer": "关注开源社区、国家重大项目与产学研合作机会。",
        },
    ],
}

CAROUSEL_CARDS: List[Dict[str, Any]] = [
    {
        "type": "founder",
        "title": "Claude Shannon",
        "description": "美国数学家、电气工程师，被誉为信息论之父，他在信息的数学定义、编码与传输方面做出革命性贡献。",
        "icon": "👤",
        "meta": [
            {"label": "身份", "value": "信息论创始人"},
            {"label": "主要贡献", "value": "信息论、密码学"},
        ],
        "tags": ["信息论", "密码学", "通信理论"],
        "to": "/shannon",
        "footer": "了解更多",
        "backgroundImage": "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1920&q=80",
    },
    {
        "type": "founder",
        "title": "香农的经典著作",
        "description": "《A Mathematical Theory of Communication》(1948) - 信息论奠基之作",
        "icon": "📚",
        "meta": [
            {"label": "发表年份", "value": "1948"},
            {"label": "论文数量", "value": "3"},
        ],
        "tags": ["经典著作", "信息论", "数学理论"],
        "to": "/shannon",
        "footer": "查看详情",
        "backgroundImage": "https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=1920&q=80",
    },
    {
        "type": "application",
        "title": "自动驾驶感知系统",
        "description": "融合视觉、雷达与高精地图实现环境感知与决策。",
        "icon": "🚀",
        "meta": [
            {"label": "行业", "value": "智能交通"},
            {"label": "覆盖范围", "value": "200+ 城市测试"},
        ],
        "tags": ["自动驾驶", "信息融合"],
        "to": "/applications",
        "footer": "查看应用",
        "backgroundImage": "https://images.unsplash.com/photo-1518770660439-4636190af475?w=1920&q=80",
    },
    {
        "type": "application",
        "title": "智能医疗影像诊断",
        "description": "基于深度神经网络实现 CT、MRI 的辅助诊断。",
        "icon": "🚀",
        "meta": [
            {"label": "行业", "value": "智慧医疗"},
            {"label": "准确率", "value": "95%"},
        ],
        "tags": ["医疗", "智能诊断"],
        "to": "/applications",
        "footer": "查看应用",
        "backgroundImage": "https://images.unsplash.com/photo-1485827404703-89b55fcc595e?w=1920&q=80",
    },
]

VERSION_LOG: List[Dict[str, Any]] = [
    {
        "version": "2.1.0",
        "date": "2025-12-28",
        "summary": "优化用户体验，增强内容展示与交互功能。",
        "highlights": [
            "应用领域页面改为左右布局，左侧文字右侧图片",
            "轮播图支持背景图片与透明卡片效果",
            "优化登录注册弹窗，修复类型检查警告",
            "完善响应式布局，提升移动端体验",
        ],
    },
    {
        "version": "2.0.1",
        "date": "2025-12-20",
        "summary": "修复已知问题，优化性能。",
        "highlights": [
            "修复版本时间轴显示问题",
            "优化页面加载性能",
            "修复移动端样式问题",
        ],
    },
    {
        "version": "2.0.0",
        "date": "2025-12-15",
        "summary": "平台全面升级，引入水平时间轴与增强交互体验。",
        "highlights": [
            "版本更新采用水平时间轴展示，更直观清晰",
            "优化讨论区卡片交互，提升用户体验",
            "完善响应式设计，适配移动端",
            "重构用户信息展示为弹窗模式",
        ],
    },
    {
        "version": "1.3.1",
        "date": "2025-12-05",
        "summary": "修复轮播图相关问题，优化数据获取。",
        "highlights": [
            "修复轮播图宽度溢出问题",
            "优化后台数据接口响应速度",
            "完善错误处理机制",
        ],
    },
    {
        "version": "1.3.0",
        "date": "2025-12-01",
        "summary": "新增轮播图功能与首页内容优化。",
        "highlights": [
            "首页添加精选内容轮播图",
            "轮播图支持全屏宽度与背景图片",
            "优化首页布局，移除冗余卡片",
            "所有内容数据从后台接口获取",
        ],
    },
    {
        "version": "1.2.1",
        "date": "2025-11-25",
        "summary": "优化未来展望模块交互体验。",
        "highlights": [
            "优化图表加载性能",
            "修复数据展示异常问题",
            "改进用户交互反馈",
        ],
    },
    {
        "version": "1.2.0",
        "date": "2025-11-20",
        "summary": "增强未来展望模块，添加趋势图表与路线图。",
        "highlights": [
            "集成 ECharts 实现多指标趋势可视化",
            "新增技术路线图展示未来发展方向",
            "优化数据展示与交互逻辑",
        ],
    },
    {
        "version": "1.1.1",
        "date": "2025-11-18",
        "summary": "修复应用领域模块问题，优化筛选功能。",
        "highlights": [
            "修复应用案例筛选逻辑",
            "优化情感审核性能",
            "完善错误提示信息",
        ],
    },
    {
        "version": "1.1.0",
        "date": "2025-11-15",
        "summary": "新增应用领域模块与情感审核机制。",
        "highlights": [
            "应用案例支持筛选与趋势可视化",
            "后端引入 NLP 情感与敏感词审核",
            "完善应用领域数据模型",
        ],
    },
    {
        "version": "1.0.1",
        "date": "2025-11-12",
        "summary": "修复基础功能问题，优化用户体验。",
        "highlights": [
            "修复讨论区发帖功能",
            "优化用户认证流程",
            "完善页面导航逻辑",
        ],
    },
    {
        "version": "1.0.0",
        "date": "2025-11-10",
        "summary": "完成基础展示模块与讨论区的原型实现。",
        "highlights": [
            "上线首页、学科简介、五大要素等核心页面",
            "讨论区支持发帖、回复与搜索",
            "建立基础架构与数据模型",
            "实现用户认证与权限管理",
        ],
    },
]

TEAM_MEMBERS: List[Dict[str, Any]] = [
    {
        "id": 1,
        "name": "李华",
        "role": "项目负责人",
        "skills": ["前端架构", "项目管理"],
        "contact": {"email": "lihua@example.com"},
    },
    {
        "id": 2,
        "name": "王伟",
        "role": "后端工程师",
        "skills": ["Flask", "数据库", "数据分析"],
        "contact": {"email": "wangwei@example.com"},
    },
    {
        "id": 3,
        "name": "陈静",
        "role": "UI/UX 设计师",
        "skills": ["交互设计", "视觉设计"],
        "contact": {"email": "chenjing@example.com"},
    },
]

POSTS: List[Dict[str, object]] = [
    {
        "id": next(_post_id_counter),
        "title": "信息工程学的核心要素有哪些？",
        "content": "从理论到实践，信息工程学强调生成、传递、收集、存储与处理。",
        "author": "Alice",
        "tags": ["理论", "基础"],
        "created_at": datetime(2025, 11, 1, 9, 30).isoformat(),
        "likes": 12,
        "replies": [
            {
                "id": 1,
                "author": "Frank",
                "content": "总结得太清楚了，特别是对信息生成和处理的拆解，读完对整条链路的理解更透彻了！",
                "created_at": datetime(2025, 11, 4, 10, 15).isoformat(),
            },
            {
                "id": 2,
                "author": "Grace",
                "content": "推荐再补充一些具体案例，比如智慧城市的数据采集流程，会更具象。",
                "created_at": datetime(2025, 11, 4, 11, 20).isoformat(),
            },
        ],
    },
    {
        "id": next(_post_id_counter),
        "title": "无人机在信息工程领域的实践",
        "content": "分享一个基于多传感器数据融合的无人机项目案例。",
        "author": "Bob",
        "tags": ["应用", "无人机"],
        "created_at": datetime(2025, 11, 3, 14, 12).isoformat(),
        "likes": 8,
        "replies": [
            {
                "id": 1,
                "author": "Carol",
                "content": "请问数据链路如何保障实时性？",
                "created_at": datetime(2025, 11, 3, 15, 5).isoformat(),
            },
            {
                "id": 2,
                "author": "David",
                "content": "我们在巡检项目里也用到了多源融合，分享的经验非常实用，期待后续更新。",
                "created_at": datetime(2025, 11, 4, 9, 45).isoformat(),
            },
            {
                "id": 3,
                "author": "Eve",
                "content": "能否附上传感器选型和网络架构图？这样方便大家对标实践。",
                "created_at": datetime(2025, 11, 4, 13, 10).isoformat(),
            },
        ],
    },
]

SESSIONS: Dict[str, int] = {}


def _ensure_data_dir() -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)


def _default_users() -> Dict[str, Any]:
    return {
        "next_id": 2,
        "users": [
            {
                "id": 1,
                "username": "admin",
                "password_hash": generate_password_hash("admin123"),
                "avatar": "https://example.com/avatar/admin.png",
                "bio": "信息工程学展示平台管理员。",
                "created_at": datetime(2025, 10, 1, 8, 0).isoformat(),
            }
        ],
    }


def _default_comments() -> Dict[str, Any]:
    return {"next_id": 1, "comments": []}


def _ensure_file(path: Path, default_factory) -> None:
    _ensure_data_dir()
    if not path.exists():
        data = default_factory()
        path.write_text(
            json.dumps(data, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )


def _load_json(path: Path, default_factory) -> Dict[str, Any]:
    _ensure_file(path, default_factory)
    with path.open(encoding="utf-8") as fp:
        return json.load(fp)


def _save_json(path: Path, data: Dict[str, Any]) -> None:
    _ensure_data_dir()
    path.write_text(
        json.dumps(data, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )


def _load_users_data() -> Dict[str, Any]:
    return _load_json(USERS_FILE, _default_users)


def _save_users_data(data: Dict[str, Any]) -> None:
    _save_json(USERS_FILE, data)


def _load_comments_data() -> Dict[str, Any]:
    return _load_json(COMMENTS_FILE, _default_comments)


def _save_comments_data(data: Dict[str, Any]) -> None:
    _save_json(COMMENTS_FILE, data)


def list_posts(keyword: Optional[str] = None, author_id: Optional[int] = None) -> List[Dict[str, object]]:
    results = POSTS
    
    # 按作者ID过滤
    if author_id is not None:
        results = [
            post for post in results
            if post.get("author_id") == author_id
        ]
    
    # 按关键字搜索
    if keyword:
        keyword_lower = keyword.lower()
        results = [
            post
            for post in results
            if keyword_lower in post["title"].lower()
            or keyword_lower in post["content"].lower()
            or any(keyword_lower in tag.lower() for tag in post.get("tags", []))
        ]
    
    return results


def get_post(post_id: int) -> Optional[Dict[str, object]]:
    return next((post for post in POSTS if post["id"] == post_id), None)


def create_post(payload: Dict[str, object]) -> Dict[str, object]:
    new_post = {
        "id": next(_post_id_counter),
        "title": payload["title"],
        "content": payload["content"],
        "author": payload.get("author", "匿名用户"),
        "author_id": payload.get("author_id"),  # 添加author_id字段
        "tags": payload.get("tags", []),
        "created_at": datetime.utcnow().isoformat(),
        "likes": 0,
        "replies": [],
    }
    POSTS.insert(0, new_post)
    return new_post


def add_reply(post_id: int, payload: Dict[str, object]) -> Optional[Dict[str, object]]:
    post = get_post(post_id)
    if post is None:
        return None

    replies: List[Dict[str, object]] = post.setdefault("replies", [])
    reply_id = len(replies) + 1
    reply = {
        "id": reply_id,
        "author": payload.get("author", "匿名用户"),
        "content": payload["content"],
        "created_at": datetime.utcnow().isoformat(),
    }
    replies.append(reply)
    return reply


def create_user(user: Dict[str, Any]) -> Dict[str, Any]:
    data = _load_users_data()
    new_user = {
        "id": data["next_id"],
        "username": user.get("username") or user.get("email"),  # 兼容旧数据
        "email": user.get("email") or user.get("username"),  # 支持邮箱
        "password_hash": user["password_hash"],
        "avatar": user.get("avatar"),
        "bio": user.get("bio"),
        "created_at": datetime.utcnow().isoformat(),
    }
    data["next_id"] += 1
    data["users"].append(new_user)
    _save_users_data(data)
    return new_user


def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
    """根据用户名或邮箱查找用户（兼容旧数据）"""
    data = _load_users_data()
    return next(
        (user for user in data["users"] 
         if user.get("username") == username or user.get("email") == username),
        None,
    )


def get_user_by_email(email: str) -> Optional[Dict[str, Any]]:
    """根据邮箱查找用户"""
    data = _load_users_data()
    return next(
        (user for user in data["users"] if user.get("email") == email),
        None,
    )


def get_user(user_id: int) -> Optional[Dict[str, Any]]:
    data = _load_users_data()
    return next((user for user in data["users"] if user["id"] == user_id), None)


def create_session(token: str, user_id: int) -> None:
    SESSIONS[token] = user_id


def get_user_id_by_token(token: str) -> Optional[int]:
    return SESSIONS.get(token)


def create_comment(payload: Dict[str, Any]) -> Dict[str, Any]:
    data = _load_comments_data()
    comment = {
        "id": data["next_id"],
        "author_id": payload["author_id"],
        "target_type": payload["target_type"],
        "target_id": payload["target_id"],
        "content": payload["content"],
        "created_at": datetime.utcnow().isoformat(),
    }
    data["next_id"] += 1
    data["comments"].append(comment)
    _save_comments_data(data)
    return comment


def list_comments(
    target_type: Optional[str] = None,
    target_id: Optional[str] = None,
    author_id: Optional[int] = None,
) -> List[Dict[str, Any]]:
    data = _load_comments_data()
    results = data["comments"]
    if target_type:
        results = [item for item in results if item["target_type"] == target_type]
    if target_id:
        results = [item for item in results if str(item["target_id"]) == str(target_id)]
    if author_id is not None:
        results = [item for item in results if item.get("author_id") == author_id]
    return results


def get_introduction() -> Dict[str, Any]:
    return INTRODUCTION


def get_founder_profile() -> Dict[str, Any]:
    return FOUNDER_PROFILE


def list_elements() -> List[Dict[str, Any]]:
    return ELEMENTS


def get_element(element_id: str) -> Optional[Dict[str, Any]]:
    return next((element for element in ELEMENTS if element["id"] == element_id), None)


def list_applications(
    industry: Optional[str] = None,
    keyword: Optional[str] = None,
    tag: Optional[str] = None,
) -> List[Dict[str, Any]]:
    items = APPLICATIONS.copy()
    if industry:
        items = [item for item in items if item["industry"] == industry]
    if tag:
        items = [
            item for item in items if any(tag.lower() == t.lower() for t in item["tags"])
        ]
    if keyword:
        keyword_lower = keyword.lower()
        items = [
            item
            for item in items
            if keyword_lower in item["title"].lower()
            or keyword_lower in item["summary"].lower()
            or any(keyword_lower in tech.lower() for tech in item["technologies"])
        ]
    
    # 格式化返回数据，将 metrics 转换为 meta 格式
    METRIC_LABELS = {
        "coverage": "覆盖范围",
        "latency": "网络时延",
        "accuracy": "准确率",
        "hospitals": "合作医院",
        "devices": "连接设备",
        "downtime": "停机变化",
        "robots": "机器人数量",
        "效率提升": "效率提升",
        "飞行架次": "飞行架次",
        "响应时间": "响应时间",
        "覆盖线路": "覆盖线路",
        "隐患识别率": "隐患识别率",
    }
    
    formatted_items = []
    for item in items:
        formatted_item = item.copy()
        # 构建 meta 数组
        meta = [{"label": "行业", "value": item.get("industry", "未注明")}]
        # 将 metrics 转换为 meta
        if item.get("metrics"):
            for key, value in item["metrics"].items():
                meta.append({
                    "label": METRIC_LABELS.get(key, key),
                    "value": value,
                })
        formatted_item["meta"] = meta
        formatted_items.append(formatted_item)
    
    return formatted_items


def get_future_insights() -> Dict[str, Any]:
    return FUTURE_INSIGHTS


def get_version_log() -> List[Dict[str, Any]]:
    return VERSION_LOG


def get_carousel_cards() -> List[Dict[str, Any]]:
    """
    获取首页轮播图卡片数据。
    返回的卡片数据会根据实际情况动态更新（如最新帖子）。
    """
    cards = CAROUSEL_CARDS.copy()
    
    # 获取最新帖子，如果有则替换最后一个卡片或添加
    posts = list_posts()
    if posts:
        # 按创建时间排序，获取最新的帖子
        sorted_posts = sorted(
            posts,
            key=lambda x: x.get("created_at", ""),
            reverse=True
        )
        if sorted_posts:
            latest_post = sorted_posts[0]
            content = latest_post.get("content", "")
            description = content[:100] + "..." if len(content) > 100 else content
            
            created_at = latest_post.get("created_at", "")
            date_str = created_at[:10] if created_at and len(created_at) >= 10 else ""
            
            post_card = {
                "type": "post",
                "title": latest_post.get("title", ""),
                "description": description,
                "icon": "💬",
                "meta": [
                    {"label": "作者", "value": latest_post.get("author", "匿名用户")},
                    {"label": "发布时间", "value": date_str},
                    {"label": "点赞", "value": str(latest_post.get("likes", 0))},
                    {"label": "回复", "value": str(len(latest_post.get("replies", [])))},
                ],
                "tags": latest_post.get("tags", []),
                "to": f"/forum/{latest_post.get('id')}",
                "footer": "查看帖子",
                "backgroundImage": "https://images.unsplash.com/photo-1522202176988-66273c2fd55f?w=1920&q=80",
            }
            # 替换最后一个卡片或添加
            if len(cards) >= 5:
                cards[-1] = post_card
            else:
                cards.append(post_card)
    
    return cards


def get_team_members() -> List[Dict[str, Any]]:
    return TEAM_MEMBERS


def search_all(keyword: str) -> Dict[str, List[Dict[str, Any]]]:
    keyword_lower = keyword.lower()

    section_results = [
        section
        for section in SECTIONS
        if keyword_lower in section["title"].lower()
        or keyword_lower in section["description"].lower()
    ]

    post_results = list_posts(keyword=keyword)

    application_results = [
        app
        for app in APPLICATIONS
        if keyword_lower in app["title"].lower()
        or keyword_lower in app["summary"].lower()
        or any(keyword_lower in tag.lower() for tag in app["tags"])
    ]

    return {
        "sections": section_results,
        "posts": post_results,
        "applications": application_results,
    }

